package com.wjs.gulimall.gulimallproduct.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wjs.gulimall.gulimallproduct.VO.AttrGroupRelationVo;
import com.wjs.gulimall.gulimallproduct.VO.AttrRespVo;
import com.wjs.gulimall.gulimallproduct.VO.AttrVo;
import com.wjs.gulimall.gulimallproduct.dao.AttrAttrgroupRelationDao;
import com.wjs.gulimall.gulimallproduct.dao.AttrGroupDao;
import com.wjs.gulimall.gulimallproduct.dao.CategoryDao;
import com.wjs.gulimall.gulimallproduct.entity.AttrAttrgroupRelationEntity;
import com.wjs.gulimall.gulimallproduct.entity.AttrGroupEntity;
import com.wjs.gulimall.gulimallproduct.entity.CategoryEntity;
import com.wjs.gulimall.gulimallproduct.service.CategoryService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.wjs.gulimall.gulimallproduct.dao.AttrDao;
import com.wjs.gulimall.gulimallproduct.entity.AttrEntity;
import com.wjs.gulimall.gulimallproduct.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;

    @Autowired
    private CategoryDao categoryDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        //将属性注入到attrEntity中
        BeanUtils.copyProperties(attr, attrEntity);
        //创建属性分组关联实体
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        this.save(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrType.ATTR_TYPE_BASE.getCode() &&attr.getAttrGroupId()!=null) {
            relationEntity.setAttrId(attrEntity.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //插入数据
            attrAttrgroupRelationDao.insert(relationEntity);
        }

    }

    @Override
    public PageUtils quertBaseList(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("attr_type", "base".equalsIgnoreCase(type) ? 1 : 0);
        if (catelogId != 0) {
            queryWrapper.eq("catelog_id", catelogId);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params),
                queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        //对拿到的数据进行stream流处理
        List<AttrRespVo> collects = records.stream().map((attrEntity) -> {
            //返回实体
            AttrRespVo attrRespVo = new AttrRespVo();
            //复制属性
            BeanUtils.copyProperties(attrEntity, attrRespVo);
            //根据分类ID查询分类名称
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            attrRespVo.setCatelogName(categoryEntity.getName());
            //根据属性id查询分组id
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (relationEntity != null) {
                Long attrGroupId = relationEntity.getAttrGroupId();
                //若分组id不为空
                if (attrGroupId != null) {
                    //更具分组id查询出分组名称
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                    attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(collects);
        return pageUtils;
    }

    @Override
    @Cacheable(value = "attr",key = "'attrinfo:'+#root.args[0]")
    public AttrRespVo getInfoById(Long attrId) {
        AttrRespVo attrVo = new AttrRespVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, attrVo);
        //根据属性id查询分组id
        AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
        if (relationEntity != null) {
            Long attrGroupId = relationEntity.getAttrGroupId();
            if (attrGroupId != null) {
                //更具分组id查询出分组名称
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
                attrVo.setGroupName(attrGroupEntity.getAttrGroupName());
                attrVo.setAttrGroupId(attrGroupId);
            }
        }
        Long[] catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
        CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
        if (categoryEntity != null) {
            attrVo.setCatelogName(categoryEntity.getName());
        }
        attrVo.setCatelogPath(catelogPath);
        return attrVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        //判断属性类型是否为基本属性
        if (attr.getAttrType() == ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()) {
            Long attrGroupId = attr.getAttrGroupId();
            Long attrId = attr.getAttrId();
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attrId);
            relationEntity.setAttrGroupId(attrGroupId);
            //查询属性分组关联表里面有没有数据
            Integer count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            //有数据就做更改操作
            if (count > 0) {
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            } else {
                //没有数据就做新增操作
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }

    }

    /**
     * 根据分组id查出其分组下所有属性
     * @param id
     * @return
     */
    @Override
    public List<AttrEntity> getRelationList(Long id) {
        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", id));
        //获取属性id集合
        List<Long> idList = relationEntityList.stream().map((obj) -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        if (idList != null && idList.size() > 0) {
            Collection<AttrEntity> attrEntities = this.listByIds(idList);
            return (List<AttrEntity>) attrEntities;
        }
        return null;
    }

    @Override
    public void deleteRelation(AttrGroupRelationVo[] vos) {
        List<AttrGroupRelationVo> relationVos = Arrays.asList(vos);
        //对参数进行stream处理
        List<AttrAttrgroupRelationEntity> relationEntityList = relationVos.stream().map((obj) -> {
            AttrAttrgroupRelationEntity relation = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(obj, relation);
            return relation;
        }).collect(Collectors.toList());
        attrAttrgroupRelationDao.deleteBatchRelation(relationEntityList);
    }

    @Override
    public PageUtils getNoRelationList(Map<String, Object> params, Long id) {
        // 当前分组只能关联自己所属的分类里的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(id);
        Long catelogId = attrGroupEntity.getCatelogId();
        //当前分组只能关联没有引用的的那些数据
        List<AttrGroupEntity> groupList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //2查询这些分类关联的属性
        //2.1 拿到分组id的集合
        List<Long> groupIdList = groupList.stream().map((obj) -> {
            return obj.getAttrGroupId();
        }).collect(Collectors.toList());
        //2.2 拿到管理这些分组的属性集合
        List<AttrAttrgroupRelationEntity> relationList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIdList));
        //2.3 拿到关联了分组的属性id集合
        List<Long> attrIdList = relationList.stream().map((obj) -> {
            return obj.getAttrId();
        }).collect(Collectors.toList());
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(attrIdList!=null&&attrIdList.size()>0){
            wrapper.notIn("attr_id", attrIdList);
        }
        wrapper.eq("catelog_id",catelogId);
        wrapper.ne("attr_type", ProductConstant.AttrType.ATTR_TYPE_SALE.getCode());
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        return new PageUtils(page);
    }

    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        List<Long> result=this.baseMapper.selectSearchAttrIds(attrIds);
        return result;
    }

}